package com.qianbao.qianbaobusiness.ui.mine.qrcode;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.androidbase.dialog.LoadingDialog;
import com.androidbase.utils.AndroidUtils;
import com.androidbase.utils.RxUtils;
import com.androidbase.utils.ToastUtils;
import com.baseandroid.config.Constant;
import com.baseandroid.config.Global;
import com.baseandroid.mvp.BaseMvpActivity;
import com.baseandroid.retrofit.RxObserver;
import com.baseandroid.utils.PhoneNumTools;
import com.qianbao.mobilecashier.PayResultCallBack;
import com.qianbao.mobilecashier.QBPaySDK;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.help.PcdDialogHelper;
import com.qianbao.qianbaobusiness.help.PermissionDialogHelper;
import com.qianbao.qianbaobusiness.json.AliPayResultBean;
import com.qianbao.qianbaobusiness.json.ApplyDownLoadCount;
import com.qianbao.qianbaobusiness.json.CheckUpdate;
import com.qianbao.qianbaobusiness.json.JumpBean;
import com.qianbao.qianbaobusiness.json.MerchantInfo;
import com.qianbao.qianbaobusiness.json.PcdBean;
import com.qianbao.qianbaobusiness.json.QRCardPayBean;
import com.qianbao.qianbaobusiness.json.SaveQrcodeBean;
import com.qianbao.qianbaobusiness.json.UserInfo;
import com.qianbao.qianbaobusiness.ui.qrcode.SaveCompleteActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 申请二维码
 */
public class ApplyQrCardActivity extends BaseMvpActivity<ApplyQrCardView, ApplyQrcodePresenter>
        implements ApplyQrCardView, PcdDialogHelper.DistrictSelectedListener {
    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack; //返回
    @BindView(R.id.toolbar_title)
    TextView       toolbarTitle; //标题
    @BindView(R.id.tv_print_byself)
    TextView       tvPrintByself;    //自行打印
    @BindView(R.id.tv_by_official)
    TextView       tvByOfficial;     //官方寄送
    @BindView(R.id.viewflipper_qr)
    ViewFlipper    viewflipperQr; //页面切换
    @BindView(R.id.bt_sava_qr_code)
    Button         btSavaQrCode; //保存图片
    @BindView(R.id.tv_free_count)
    TextView       tvFreeCount;
    @BindView(R.id.tv_select_addr)
    TextView       mTvAddPcd;     //选择地址
    @BindView(R.id.et_name)
    EditText       mEtName;   //姓名输入框
    @BindView(R.id.ed_phoneNum)
    EditText       mEtPhoneNum;   //手机号输入框
    @BindView(R.id.ed_addr_detail)
    EditText       mEtAddDetail; //详细地址
    @BindView(R.id.tv_qr_card_count)
    TextView       tvQrCardCount;        //收款码价
    @BindView(R.id.bt_agree_submit)
    Button         btAgreeSubmit;      //同意并提交

    private SaveQrcodeBean                 bean;
    private QRCardPayBean.MerOrderInfoBean merOrderInfoBean;
    private LoadingDialog                  mLoadingDialog;
    private String mDownLoadFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
    private String          mDownLoadFileName;
    private PcdDialogHelper pcdDialogHelper;
    private String          mName;
    private String          mPhone;
    private String          mAddrDetail;
    private String          mProvinceName;
    private String          mCityName;
    private String          mDistrictName;
    private MerchantInfo    merchantInfo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_qr_code;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        QBPaySDK.getInstance().initSDK(this);
        EventBus.getDefault().register(this);
        toolbarTitle.setText(AndroidUtils.getContext()
                                     .getResources().getString(R.string.apply_qr_card));
        tvPrintByself.setSelected(true);
        tvByOfficial.setSelected(false);
        tvPrintByself.setSelected(true);
        getPresenter().checkUpdate();
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        merchantInfo = (MerchantInfo) getIntent().getSerializableExtra("mSelectedMerchant");
        pcdDialogHelper = new PcdDialogHelper(this, this);
        /**
         * 姓名输入监听
         */
        UserInfo.User user = Global.getUserInfoBean().getUser();
        mName = user.getUserName();
        mEtName.setText(TextUtils.isEmpty(mName) ? "" : mName);
        mEtName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mName = s.toString().trim();
            }
        });

        /**
         * 手机号输入监听
         */
        mPhone = user.getMobile();
        mEtPhoneNum.setText(TextUtils.isEmpty(mPhone) ? "" : mPhone);
        mEtPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mPhone = s.toString().trim();
            }
        });

        /**
         * 详细地址输入监听
         */
        boolean b = merchantInfo.shopAddress == null || TextUtils.isEmpty(merchantInfo.shopAddress);
        mEtAddDetail.setText(b ? "请输入详细地址" : merchantInfo.shopAddress);
        mAddrDetail = b ? "" : merchantInfo.shopAddress;
        mEtAddDetail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mAddrDetail = s.toString().trim();
            }
        });
        mProvinceName = merchantInfo.shopProviceName;
        mCityName = merchantInfo.shopCityName;
        mDistrictName = merchantInfo.shopDistrictName;
        if (!TextUtils.isEmpty(mProvinceName) && !TextUtils.isEmpty(mCityName) && !TextUtils.isEmpty(mDistrictName)) {
            mTvAddPcd.setText(merchantInfo.shopProviceName + " " + merchantInfo.shopCityName + " " + merchantInfo.shopDistrictName);
        }
    }

    @OnClick({R.id.toolbar_back, R.id.tv_print_byself, R.id.tv_by_official, R.id.bt_sava_qr_code
            , R.id.tv_select_addr, R.id.bt_agree_submit})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                finish();
                break;

            case R.id.tv_print_byself:   //自行打印
                if (tvPrintByself.isSelected()) {
                    return;
                }
                tvByOfficial.setSelected(false);
                tvPrintByself.setSelected(true);
                viewflipperQr.showNext();
                break;

            case R.id.tv_by_official:     //官方寄送
                if (tvByOfficial.isSelected()) {
                    return;
                }
                tvByOfficial.setSelected(true);
                tvPrintByself.setSelected(false);
                viewflipperQr.showPrevious();
                break;

            case R.id.bt_sava_qr_code:
                if (bean != null && !TextUtils.isEmpty(bean.actualUrl)) {
                    if (bean.count.equals("0")) {
                        ToastUtils.showLongToast("每天最多可下载10次");
                        return;
                    }
                    startDownLoad();
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        saveQrCodeClick();
                    } else {
                        getPresenter().saveQrcode(Global.getQrCardSelectedMerchantNo());
                    }
                }
                break;

            case R.id.tv_select_addr:
                pcdDialogHelper.createDialog();
                break;

            case R.id.bt_agree_submit:     //同意并提交
                if (TextUtils.isEmpty(mName)) {
                    ToastUtils.showLongToast("请填写姓名");
                    return;
                }
                if (TextUtils.isEmpty(mPhone)) {
                    ToastUtils.showLongToast("请填写手机号");
                    return;
                }
                if (!PhoneNumTools.isMobile(mPhone)) {
                    ToastUtils.showLongToast("请正确填写手机号");
                    return;
                }
                if (TextUtils.isEmpty(mProvinceName) || TextUtils.isEmpty(mCityName) || TextUtils.isEmpty(mDistrictName)) {
                    ToastUtils.showLongToast("请选择地区");
                    return;
                }
                if (TextUtils.isEmpty(mAddrDetail)) {
                    ToastUtils.showLongToast("请填写详细地址");
                    return;
                }
                getPresenter().createOrder(Global.getUserInfoBean().getUser().getUserNo()
                        , Global.getQrCardSelectedMerchantNo()
                        , merchantInfo.posMerchantNo, Constant.DEFAULT_QR_MONEY, mName, mPhone, mProvinceName, mCityName, mDistrictName, mAddrDetail);
                break;
            default:
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void saveQrCodeClick() {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            getPresenter().saveQrcode(Global.getQrCardSelectedMerchantNo());
        } else {
            RxPermissions rxPermissions = new RxPermissions(this);
            rxPermissions.request(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .compose(RxUtils.<Boolean>applySchedulersLifeCycle(getMvpView()))
                    .subscribe(new RxObserver<Boolean>() {
                        @Override
                        public void onNext(Boolean granted) {
                            if (granted) {
                                getPresenter().saveQrcode(Global.getQrCardSelectedMerchantNo());
                            } else {
                                new PermissionDialogHelper(ApplyQrCardActivity.this).setMsg("请打开文件读取权限").show();
                            }
                        }
                    });
        }
    }

    @Override
    public void onSuccess(SaveQrcodeBean result) {
        if (result == null) {
            return;
        }
        bean = result;
        tvFreeCount.setText(Html.fromHtml("今天还能免费下载" + "<font color='#ff4a4a'>"
                                                  + bean.count + "</font>" + "次"));
        startDownLoad();
    }

    private void startDownLoad() {
        mDownLoadFileName = bean.actualUrl.substring(bean.actualUrl.lastIndexOf("/"));
        if (TextUtils.isEmpty(mDownLoadFolder)) {
            return;
        }
        getPresenter().requestDownload(bean.actualUrl, mDownLoadFolder, mDownLoadFileName);
    }

    @Override
    public void showLoadingDialog() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog();
        }

        if (!mLoadingDialog.isVisible()) {
            mLoadingDialog.show(getSupportFragmentManager(), "loadingdialog");
        }
    }

    @Override
    public void closeLoadingDialog() {
        mLoadingDialog.dismissAllowingStateLoss();
    }

    @Override
    public void downloadCompleted() {
        bean.actualUrl = "";
        File out = new File(mDownLoadFolder, mDownLoadFileName);
        try {
            MediaStore.Images.Media.insertImage(this.getContentResolver(), out.getAbsolutePath(), mDownLoadFileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(this, getPackageName() + "" + ".fileprovider", out);
        } else {
            uri = Uri.fromFile(out);
        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        ToastUtils.showLongToast("保存成功");
        SaveCompleteActivity.start(this, bean.actualUrl);
    }

    @Override
    public void downloadFailed() {
        ToastUtils.showLongToast(R.string.start_file_download_error);
        closeLoadingDialog();
    }

    @Override
    public void creatOrderSuccess(QRCardPayBean result) {
        merOrderInfoBean = result.getMerOrderInfo();
        showPaySdk(result.getResult().getCashierId()
                , result.getResult().getCashierToken()
                , result.getResult().getCashierEnv());
    }

    @Override
    public void getDownLoadCount(ApplyDownLoadCount result) {
        if (bean == null) {
            bean = new SaveQrcodeBean();
        }
        bean.count = result.getCount();
        tvFreeCount.setText(Html.fromHtml("今天还能免费下载" + "<font color='#ff4a4a'>"
                                                  + bean.count + "</font>" + "次"));
    }

    @Override
    public void getOrderStatus(AliPayResultBean result) {
        if (result.getOrderStatus().equals(Constant.PAY_SUCCESS)) {
            Intent intent = new Intent(ApplyQrCardActivity.this, PayResultActivity.class);
            intent.putExtra("code", Constant.PAY_SUCCESS);
            startActivity(intent);
        } else {
            Intent intent = new Intent(ApplyQrCardActivity.this, PayResultActivity.class);
            intent.putExtra("code", Constant.PAY_FAILED);
            startActivity(intent);
        }
    }

    @Override
    public void OnVersionUpdate(CheckUpdate result) {
        tvQrCardCount.setText((Html.fromHtml("收款码价：" + "<font color='#ff4a4a'>"
                                                     + "¥ " + result.getQrcode_account() + "元" + "</font>")));
    }

    @Override
    public void OnVersionUpdateError() {

    }

    @Override
    public void itemSelected(PcdBean.ProvincesBean province, PcdBean.CitysBean city, PcdBean.DistrictsBean district) {
        mTvAddPcd.setText(province.getName() + " " + city.getName() + " " + district.getName());
        mProvinceName = province.getName();
        mCityName = city.getName();
        mDistrictName = district.getName();
    }

    private void showPaySdk(String cashierId, String cashierToken, String cashierEnv) {
        QBPaySDK.getInstance().callPaySDK(cashierId, cashierToken, cashierEnv, new PayResultCallBack() {

            @Override
            public void success(String code, String status) {
                Intent intent = new Intent(ApplyQrCardActivity.this, PayResultActivity.class);
                intent.putExtra("code", Constant.PAY_SUCCESS);
                startActivity(intent);
            }

            @Override
            public void paying(String code, String status) {
                getPresenter().getOrderById(merOrderInfoBean.getId());
            }

            @Override
            public void failed(String code, String message) {
                Intent intent = new Intent(ApplyQrCardActivity.this, PayResultActivity.class);
                intent.putExtra("code", Constant.PAY_FAILED);
                startActivity(intent);
            }

            @Override
            public void cancel(String s) {
                ToastUtils.showLongToast("取消付款");
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        QBPaySDK.getInstance().onResume();
        getPresenter().getQrcodeDownloadCount();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(JumpBean jumpBean) {
        if (jumpBean.getTag().equals("complete")) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
